import random

from django.shortcuts import render, HttpResponse, redirect
from restaurant.models import MenuItem, Order, Details,Comment
from restaurant.form import OrderForm
from user.models import UserInfo


def get_unique_categories():
    # 获取去重后的分类集合
    unique_categories = MenuItem.objects.values('category').distinct()
    return unique_categories


def order_menu(request):
    uinfo = request.session.get('info')
    user_info = [0]
    if uinfo:
        user_id = uinfo['id']
        identity = UserInfo.objects.filter(id=user_id)[0].identity
        if identity == 'owner':
            return redirect('/owner/orders')
        user_info[0] = 1
    # 有POST一定是登录后（登录才能下单）
    if request.method == 'POST':
        form = OrderForm(request.POST)
        if form.is_valid():
            # 从表单中获取数据
            content = form.cleaned_data['content']
            total = form.cleaned_data['total']
            comment = form.cleaned_data['comment']
            if comment == '备注':
                comment = '无'
            guest_id = user_id
            restaurant_id = form.cleaned_data['restaurant_id']

            # 创建订单对象并保存到数据库
            order = Order(
                content=content,
                total=total,
                comment=comment,
                guest_id=guest_id,
                restaurant_id=restaurant_id
            )
            order.save()

            # 点单加已售数量
            tokens = content.strip().split(',')
            items = [t.split()[0] for t in tokens]
            for item in items:
                sold_obj = MenuItem.objects.filter(name=item).first()
                sold_obj.sold += 1
                sold_obj.save()
            this_user = UserInfo.objects.filter(id=user_id).first()
            order_objs = Order.objects.filter(guest_id=user_id)
            print(order_objs)
            info = []
            if order_objs:
                order_id = [order_obj.order_id for order_obj in order_objs]
                content = [order_obj.content for order_obj in order_objs]
                total = [order_obj.total for order_obj in order_objs]
                comment = [order_obj.comment for order_obj in order_objs]
                status = [order_obj.status for order_obj in order_objs]
                info = list(zip(order_id, content, total, comment, status))
            # 处理完订单后，重定向到某个页面或显示成功消息
            return render(request, 'user/my_order.html', {'info_list': info, 'user_info' : this_user})

    else:
        form = OrderForm()  # 创建一个空的订单表单

    menu_items = MenuItem.objects.all()
    unique_categories = get_unique_categories()
    categories = []
    for c in unique_categories:
        categories.append(c['category'])

    return render(request, 'html/order_menu.html',
                  {'menu_items': menu_items, 'category': categories, 'form': form, 'user_info': user_info})


def details(request, item_name):
    item = Details.objects.get(name=item_name)
    random_items = Details.objects.exclude(id=item.id).order_by('?')[:4]
    # 将四个项目的ID放入列表
    ran_num = [item.id for item in random_items]
    next_item = Details.objects.filter(id__in=(i for i in ran_num))
    return render(request, 'html/details.html', {'item': item, 'next_item': next_item})


def total_comments(request):
    uinfo = request.session.get('info')
    user_info = [0]
    if uinfo:
        user_id = uinfo['id']
        identity = UserInfo.objects.filter(id=user_id)[0].identity
        user_info[0] = 1
    my_set = Comment.objects.all()
    return render(request, 'html/total_comments.html', {'orders': my_set, 'user_info': user_info})



